package com.ang.mqtt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import javax.annotation.Resource;

@Configuration
public class MqttProducerConfig {

    //mqtt要发送消息的信道名称
    public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";

//    private static String ClientId = "test/producer";
//    private static String Topic = "towerTest";

    @Autowired
    MqttPahoClientFactory mqttClientFactory;

    @Resource
    MqttProperties mqttProperties;

    /**
     * MQTT信息通道（生产者）
     * 消息出站通道
     */
    @Bean(name = CHANNEL_NAME_OUT)
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * MQTT消息处理器（生产者）
     * 消息出站时处理
     */
    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperties.getClientId(), mqttClientFactory);

        //当 时true，调用者不会阻塞。相反，它在发送消息时等待传递确认。默认值为false（在确认交付之前发送阻止）。
        messageHandler.setAsync(false);
        //设置默认的qos级别
        messageHandler.setDefaultQos(1);
        //设置发布的主题
        messageHandler.setDefaultTopic(mqttProperties.getPubTopic());
        //保留标志的默认值。如果没有mqtt_retained找到标题，则使用它。如果提供了自定义，则不使用它converter。这里不启用
        messageHandler.setDefaultRetained(false);

        return messageHandler;
    }
}

